﻿using EPiAbstractions.Common.Categories;
using EPiServer.Common.Categories;
using Moq;
using StructureMap.AutoMocking;
using Xunit;

namespace JoelAbrahamsson.BlogExtensions.Tests.BlogCategoryProviderTests
{
    public class BlogCategoriesRootTests
    {
        [Fact]
        public void BlogCategoriesRoot_ReturnsCategoryWithRootName()
        {
            MoqAutoMocker<BlogCategoryProvider> blogCategoryProviderAutoMocker = new MoqAutoMocker<BlogCategoryProvider>();
            Mock<ICategoryHandlerFacade> fakeCategoryHandler = Mock.Get(blogCategoryProviderAutoMocker.Get<ICategoryHandlerFacade>());
            ICategory categoryFromHandler = new Mock<ICategory>().Object;
            fakeCategoryHandler.Setup(handler => handler.GetCategory(BlogCategoryProvider.BlogCategoriesRootName)).Returns(categoryFromHandler);

            ICategory returnedCategory = blogCategoryProviderAutoMocker.ClassUnderTest.BlogCategoriesRoot;

            Assert.Equal<ICategory>(categoryFromHandler, returnedCategory);
        }

        [Fact]
        public void RootCategoryNotYetCreated_BlogCategoriesRoot_CreatesAndReturnsCategoryWithRootName()
        {
            MoqAutoMocker<BlogCategoryProvider> blogCategoryProviderAutoMocker = new MoqAutoMocker<BlogCategoryProvider>();
            Mock<ICategoryHandlerFacade> fakeCategoryHandler = Mock.Get(blogCategoryProviderAutoMocker.Get<ICategoryHandlerFacade>());
            fakeCategoryHandler.Setup<ICategory>(handler => handler.GetCategory((string) BlogCategoryProvider.BlogCategoriesRootName)).Returns((ICategory)null);
            ICategory addedCategoryFromHandler = new Mock<ICategory>().Object;
            fakeCategoryHandler.Setup(handler => handler.AddCategory(It.IsAny<ICategory>())).Returns(addedCategoryFromHandler);

            ICategory returnedCategory = blogCategoryProviderAutoMocker.ClassUnderTest.BlogCategoriesRoot;

            fakeCategoryHandler.Verify(
                handler => handler.AddCategory(It.Is<ICategory>(category => 
                                                                category.Name == BlogCategoryProvider.BlogCategoriesRootName)));
            Assert.NotNull(returnedCategory);
            Assert.Equal<ICategory>(addedCategoryFromHandler, returnedCategory);
        }
    }
}